package com.hy.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.hy.demo.model.AccessToken;
import com.hy.demo.model.UserAccessToken;
import com.hy.demo.model.UserTag;
import com.hy.demo.model.WeChatUser;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 * @author cjl
 * @since  2020-7-24
 * @version 1.0
 */
@Slf4j
public class WeChatUtil {

    /**
     * 获取UserAccessToken实体类
     */
    public static UserAccessToken getUserAccessToken(String appId,String appSecret,String code) throws IOException {
        // 测试号信息里的appId
        log.info("appId==={}", appId);
        // 测试号信息里的appSecret
        log.info("secret==={}", appSecret);

        // 根据传入的code,拼接出访问微信定义好的接口的URL
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code
                     + "&grant_type=authorization_code";

        // 向相应URL发送请求获取token json字符串
        Map<String, String> headers = new HashMap<>();
        Connection.Response tokenStr = HttpUtils.get(url, headers);
        log.info("userAccessToken==={}", tokenStr.body());
        UserAccessToken token = null;
        try {
            token = JSON.parseObject(tokenStr.body(), UserAccessToken.class);

        } catch (Exception e) {
            log.error("获取用户accessToken失败: {}", e.getMessage());
        }
        return token;
    }

    /**
     * 获取WeChatUser实体类
     */
    public static WeChatUser getUserInfo(String accessToken, String openId) throws IOException {
        // 根据传入的accessToken以及openId拼接出访问微信定义的端口并获取用户信息的URL
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        // 访问该URL获取用户信息json 字符串
        Map<String, String> headers = new HashMap<>();
        Connection.Response userStr = HttpUtils.get(url, headers);
        WeChatUser user = null;
        try {
            user = JSON.parseObject(userStr.body(), WeChatUser.class);

        } catch (Exception e) {
            log.error("获取用户accessToken失败: {}", e.getMessage());
        }

        return user;
    }


    /**
     * 获取accessToken
     */
    public static AccessToken getAccessToken(String appId, String secret) throws IOException {

        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret;

        // 向相应URL发送请求获取token json字符串
        Map<String, String> headers = new HashMap<>();
        Connection.Response tokenStr = HttpUtils.get(url, headers);
        log.info("userAccessToken==={}", tokenStr.body());
        AccessToken token = null;
        try {
            token = JSON.parseObject(tokenStr.body(), AccessToken.class);

        } catch (Exception e) {
            log.error("获取用户accessToken失败: {}", e.getMessage());
        }
        return token;
    }


    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuilder hexStr = new StringBuilder();
            // 字节数组转换为 十六进制 数
            for (byte b : messageDigest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     *
     * TODO 稍微有些问题
     * 用户打标签
     */
    public static UserTag createTag(String accessToken,String name) throws IOException {

        String url="https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+accessToken;
        JSONObject j = new JSONObject();
        JSONObject group = new JSONObject();
        try {
            j.put("name","测试");
            group.put("group",j);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Connection.Response tagStr= HttpUtils.post(url,group.toString());

        UserTag userTag=null;
        try {
            Map map1=new HashMap();
            map1=JSON.parseObject(tagStr.body(),Map.class);
            System.out.println(tagStr.body());
            //  userTag= JSON.parseObject(map1.get("tag").toString(),UserTag.class);
        }catch (Exception e){
            log.error("用户打标签失败：{}", e.getMessage());
        }
        return userTag;
    }
}
